package com.uphone.kingmall.activity.order;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.google.zxing.WriterException;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.GoodsDetailActivity;
import com.uphone.kingmall.activity.ShopDetailActivity;
import com.uphone.kingmall.adapter.RvOrderGoodsAdapter2;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.OrderBean;
import com.uphone.kingmall.bean.OrderDetailBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.DensityUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.QRCodeUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.utils.intent.IntentUtils;
import com.uphone.kingmall.view.dialog.RadishDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//import io.rong.imkit.RongIM;
//import io.rong.imlib.model.CSCustomServiceInfo;

/**
 * <pre>
 *     author : 孙增艳
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2019/2/26
 *     desc   : 待付款页面
 *     version: 1.0
 * </pre>
 */
public class OrderDetailActivity extends BaseActivity {
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_mobile)
    TextView tvAddressMobile;
    @BindView(R.id.tv_address_content)
    TextView tvAddressContent;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.tv_order_date)
    TextView tvOrderDate;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.tv_order_freight)
    TextView tvOrderFreight;
    @BindView(R.id.tv_order_price)
    TextView tvOrderPrice;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_create_time)
    TextView tvOrderCreateTime;
    @BindView(R.id.tv_order_pay_time)
    TextView tvOrderPayTime;
    @BindView(R.id.tv_order_shipment_time)
    TextView tvOrderShipmentTime;
    @BindView(R.id.rl_dfk)
    RelativeLayout rlDfk;
    @BindView(R.id.rl_dfh)
    LinearLayout rlDfh;
    @BindView(R.id.rl_dsh_online)
    LinearLayout rlDshOnline;
    @BindView(R.id.rl_dsh)
    RelativeLayout rlDsh;
    @BindView(R.id.rl_dpj)
    RelativeLayout rlDpj;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_qxdd)
    TextView tvQxdd;
    @BindView(R.id.tv_wyfk)
    TextView tvWyfk;
    @BindView(R.id.tv_wycd)
    TextView tvWycd;
    @BindView(R.id.tv_lxsj)
    TextView tvLxsj;
    //    @BindView(R.id.tv_qxdd2)
//    TextView tvQxdd2;
    @BindView(R.id.tv_sqtk)
    TextView tvSqtk;
    @BindView(R.id.tv_lxsj2)
    TextView tvLxsj2;
    @BindView(R.id.tv_sqtk2)
    TextView tvSqtk2;
    @BindView(R.id.tv_ckwl)
    TextView tvCkwl;
    @BindView(R.id.tv_qrsh)
    TextView tvQrsh;
    @BindView(R.id.tv_xfm)
    TextView tvXfm;
    @BindView(R.id.tv_lxsj3)
    TextView tvLxsj3;
    @BindView(R.id.tv_sqtk3)
    TextView tvSqtk3;
    @BindView(R.id.tv_qpj)
    TextView tvQpj;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.rl_phone)
    FrameLayout rlPhone;
    @BindView(R.id.tv_order_installation)
    TextView tvOrderInstallation;
    @BindView(R.id.rel_installation)
    RelativeLayout relInstallation;
    @IntentData
    private int id = -1;

    private List<OrderBean.DataBean.GoodslistBean> goodsBeanList = new ArrayList<>();
    private RvOrderGoodsAdapter2 goodsAdapter2;
    private OrderDetailBean.OrderBean orderBean;
    private long timeDiv;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_waitpayorder;
    }

    @Override
    public void initView() {
        setStatusBar();

        goodsAdapter2 = new RvOrderGoodsAdapter2(this, goodsBeanList);
        rvGoods.setLayoutManager(new LinearLayoutManager(this));
        rvGoods.setAdapter(goodsAdapter2);
        goodsAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IntentUtils.getInstance()
                        .with(OrderDetailActivity.this, GoodsDetailActivity.class)
                        .putInt(ConstansUtils.ID, goodsBeanList.get(position).getGoodsId())
                        .start();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadDataNet();
    }

    @Override
    public void loadJPush() {
        super.loadJPush();
        loadDataNet();
    }

    @Override
    public void initData() {

    }

    private void loadDataNet() {
        HttpParams params = new HttpParams();
        params.put("orderId", id);
        OkGoUtils.progressRequest(MyUrl.getUserOrderInfo, this, params, new onNormalRequestListener() {

            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    OrderDetailBean bean = GsonUtils.getGson().fromJson(body, OrderDetailBean.class);
                    orderBean = bean.getOrder();
                    loadData();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void loadData() {
        // 倒计时
        daojishi();

        // 商品列表
        goodsBeanList = orderBean.getGoodslist();
        goodsAdapter2.setNewData(goodsBeanList);

        // 地址信息
        if (orderBean.getPostType() == 2) {
            //到店
            tvAddressName.setText("到店消费");
            tvAddressMobile.setVisibility(View.GONE);
            tvAddressContent.setVisibility(View.GONE);
        } else {
            tvAddressName.setText("收货人:" + orderBean.getReceiverName());
            tvAddressMobile.setText("" + orderBean.getReceiverTel());
            tvAddressContent.setText("收货地址：" + orderBean.getReceiverAddr());
            tvAddressMobile.setVisibility(View.VISIBLE);
            tvAddressContent.setVisibility(View.VISIBLE);
        }

        //订单信息
        tvShopName.setText("" + orderBean.getShopName());

        tvOrderPrice.setText("" + orderBean.getOrderFee());
        tvOrderNumber.setText("订单编号：" + orderBean.getOrderNo());
        tvOrderCreateTime.setText("创建时间：" + orderBean.getOrderTime() + "");
        tvOrderPayTime.setText("付款时间：" + orderBean.getPayTime() + "");
        tvOrderShipmentTime.setText("发货时间：" + orderBean.getSendTime());
        if (orderBean.getPostType() == 1) {
            tvOrderFreight.setText("¥" + orderBean.getPostFee());
        } else {
            tvOrderFreight.setText("¥0.00");
        }
        if (orderBean.getInstallationFee() > 0) {
            relInstallation.setVisibility(View.VISIBLE);
            tvOrderInstallation.setText("￥" + orderBean.getInstallationFee());
        } else {
            relInstallation.setVisibility(View.GONE);
        }

        //底部功能栏
        rlDfk.setVisibility(View.GONE);
        tvOrderPayTime.setVisibility(View.GONE);
        rlDfh.setVisibility(View.GONE);
        tvOrderShipmentTime.setVisibility(View.GONE);
        rlDsh.setVisibility(View.GONE);
        rlDpj.setVisibility(View.GONE);
        rlPhone.setVisibility(View.GONE);
        rlDshOnline.setVisibility(View.GONE);
        int type = orderBean.getOrderStatus();
        //	0已取消；1退款;2退货;3换货;4售后成功；10待付款；20待发货；30待收货；40待评价；50已完成
        switch (type) {
            case 0://已取消
                tvOrderState.setText("已取消");
                break;
            case 1://1退款
                rlPhone.setVisibility(View.VISIBLE);
                tvOrderState.setText("退款中");
                break;
            case 2://2退货
                rlPhone.setVisibility(View.VISIBLE);
                tvOrderState.setText("退货中");
                break;
            case 3://3换货
                rlPhone.setVisibility(View.VISIBLE);
                tvOrderState.setText("换货中");
                break;
            case 10://待付款
                rlDfk.setVisibility(View.VISIBLE);
                tvOrderState.setText("待付款");
                break;
            case 20://待发货
                tvOrderPayTime.setVisibility(View.VISIBLE);
                rlDfh.setVisibility(View.VISIBLE);
                tvOrderState.setText("待发货");
                break;
            case 30://待收货
                if (orderBean.getPostType() == 1) {
                    rlDshOnline.setVisibility(View.VISIBLE);
                } else {
                    rlDsh.setVisibility(View.VISIBLE);
                }
                tvOrderPayTime.setVisibility(View.VISIBLE);
                tvOrderShipmentTime.setVisibility(View.VISIBLE);
                tvOrderState.setText("待收货");
                break;
            case 40://去评价
                tvOrderPayTime.setVisibility(View.VISIBLE);
                tvOrderShipmentTime.setVisibility(View.VISIBLE);
                rlDpj.setVisibility(View.VISIBLE);
                tvOrderState.setText("待评价");
                break;
            case 50://已完成
                tvOrderPayTime.setVisibility(View.VISIBLE);
                tvOrderShipmentTime.setVisibility(View.VISIBLE);
                tvOrderState.setText("已完成");
                break;
            default:
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (timeDiv > 1000) {
                time(timeDiv);
            } else {
                tvOrderDate.setVisibility(View.GONE);
            }
        }
    };

    private void daojishi() {
        timeDiv = orderBean.getAutoReceiveDay();
        if (timeDiv > 0) {
            handler.sendEmptyMessage(0);
        } else {
            tvOrderDate.setVisibility(View.GONE);
        }
    }

    public void time(long seconds) {
        long day = seconds / (60 * 60 * 24 * 1000);//换成天
        long hour = (seconds - (60 * 60 * 24 * day * 1000)) / (3600 * 1000);//总秒数-换算成天的秒数=剩余的秒数    剩余的秒数换算为小时
        long minute = (seconds - 60 * 60 * 24 * day * 1000 - 3600 * hour * 1000) / (60 * 1000);//总秒数-换算成天的秒数-换算成小时的秒数=剩余的秒数    剩余的秒数换算为分
        long second = (seconds - 60 * 60 * 24 * day * 1000 - 3600 * hour * 1000 - 60 * minute * 1000) / 1000;//总秒数-换算成天的秒数-换算成小时的秒数-换算为分的秒数=剩余的秒数   
        tvOrderDate.setText("剩余 " + day + "天" + hour + "时" + minute + "分" + second + "秒" + " 自动确认收货");
        timeDiv = timeDiv - 1000;
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    @OnClick({R.id.iv_back, R.id.tv_shop_name, R.id.tv_qxdd, R.id.tv_wyfk, R.id.tv_wycd, R.id.tv_lxsj, /*R.id.tv_qxdd2, */R.id.tv_sqtk, R.id.tv_lxsj2, R.id.tv_sqtk2, R.id.tv_ckwl, R.id.tv_qrsh, R.id.tv_xfm, R.id.tv_lxsj3, R.id.tv_sqtk3, R.id.tv_qpj})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
            case R.id.tv_shop_name:
                CommonUtil.startIntent(this, ShopDetailActivity.class, orderBean.getShopId());
                break;
            case R.id.tv_qxdd://取消订单
//            case R.id.tv_qxdd2://取消订单
                showDialog(MyUrl.userCancleOrder, "取消订单");
                break;
            case R.id.tv_wyfk://我要付款
                IntentUtils.getInstance().with(this, OrderPayActivity.class)
                        .putSerializable(ConstansUtils.BEAN, orderBean).start();
                break;
            case R.id.tv_wycd://我要催单
                loadNet(MyUrl.cuidan, "催单");
                break;
            case R.id.tv_lxsj://联系商家
            case R.id.tv_phone:
            case R.id.tv_lxsj2:
            case R.id.tv_lxsj3:
//                if (orderBean != null && !TextUtils.isEmpty(orderBean.getShopPhone())) {
//                    DialogUtil.showCallDialog(this, orderBean.getShopPhone());
//                } else {
//                    //联系商家
//                    CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                    final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                    RongIM.getInstance().startCustomerServiceChat(this, ConstansUtils.CSCustomServiceId, "", csInfo);
//                }
                break;
            case R.id.tv_sqtk://申请退款
                IntentUtils.getInstance().with(this, ApplyForRefundActivity.class)
                        .putSerializable(ConstansUtils.BEAN, new OrderBean.DataBean(orderBean))
                        .putInt(ConstansUtils.TYPE, 1).start();
                break;
            case R.id.tv_sqtk2://申请退货
            case R.id.tv_sqtk3:
                IntentUtils.getInstance().with(this, ApplyForRefundActivity.class)
                        .putSerializable(ConstansUtils.BEAN, new OrderBean.DataBean(orderBean))
                        .putInt(ConstansUtils.TYPE, 2).start();

                break;
            case R.id.tv_ckwl://查询物流
                CommonUtil.startIntent(this, OrderFollowActivity.class, id);
                break;
            case R.id.tv_qrsh://确认收货
                showDialog(MyUrl.receiveOrder, "确认收货");
                break;
            case R.id.tv_xfm://消费码

                IntentUtils.getInstance().with(this, OrderCodeActivity.class)
                        .putString("checkCode", orderBean.getCheckCode()).start();
//                showqr();
                break;
            case R.id.tv_qpj://去评价
                IntentUtils.getInstance().with(this, OrderEvaluateActivity.class)
                        .putSerializable(ConstansUtils.BEAN, new OrderBean.DataBean(orderBean)).start();
                break;
            default:
                break;
        }
    }

    private void showqr() {
        View dialogView = View.inflate(this, R.layout.kingmall_dialog_qrcode, null);
        ImageView iv_qrcode = dialogView.findViewById(R.id.iv_qrcode);
        //绘制二维码
        try {
            Bitmap bitmap = QRCodeUtils.createQRCode
                    (ConstansUtils.QRCodeOrderCheck + orderBean.getCheckCode() + "", DensityUtil.dip2px(this, 260));
            iv_qrcode.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        new RadishDialog.Builder(this).setView(dialogView)
                .show();
    }

    private void showDialog(final String url, final String msg) {
        CommonUtil.showAlterDialog(this, msg + "?", new CommonUtil.OnAlterDialogCallBack() {
            @Override
            public void callBack(RadishDialog dialog, View view) {
                loadNet(url, msg);
            }
        });

    }

    private void loadNet(final String url, final String msg) {
        HttpParams params = new HttpParams();
        params.put("orderId", id);
        OkGoUtils.normalRequest(url, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    ToastUtils.showShortToast(OrderDetailActivity.this, msg + "成功");
                    if (TextUtils.equals(MyUrl.userCancleOrder, url)) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 500);
                        return;
                    }
                    loadDataNet();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
